<template>
  <div>
    <a-card class="card" :bordered="false" :style="`min-height: ${cardMinHeight}px;`">

      <!--弹窗1详情-->
      <a-modal
          destroyOnClose
          v-model='detailModal'
          width='800px'
          :title="canBeQuery?'详情':title"
          @ok="detailHandleCancel"
          @cancel="detailHandleCancel"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;display: flex;flex-direction: row;margin-top: 10px">
            <a-form-model layout="inline"  class='query' style='display: flex;flex-wrap: wrap;'>
              <a-form-model-item
                  class='optionTitle'
                  label="设备编码"
                  style="margin-left: 15px"
              >
                <a-input style='width: 200px;height: 32px' v-model='record.device_code'  :disabled="!canBeEdited || !isAdd" v-auth="`query`"></a-input>
              </a-form-model-item>
              <a-form-model-item
                  class='optionTitle'
                  label="设备名称"
                  prop="name"
              >
                <a-input style='width: 200px;height: 32px' v-model='record.device_name'  :disabled="!canBeEdited || !isAdd" v-auth="`query`"></a-input>
              </a-form-model-item>
            </a-form-model>
          </div>
          <a-form layout="inline">
            <div style="margin:15px 2%;">
              <a-form-item label="故障原因" style="width: 100%;margin: 5px 0;">
                <a-textarea v-model.trim="record.fault_reason"
                            :disabled="!canBeEdited || !isAdd"
                            show-count style="width: 550px" :maxlength="500" />
              </a-form-item>

              <a-form-item label="维修人" style="width: 100%;margin: 5px 0 5px 14px;">
                  <a-input style='width: 250px;height: 32px;'
                           :disabled="!canBeEdited || !isAdd"
                           v-model.trim="record.create_user_name"
                           v-auth="`query`" ></a-input>
              </a-form-item>
              <a-form-item label="维修日期" style="width: 100%;">
                <a-date-picker
                    format="YYYY-MM-DD"
                    show-time
                    allowClear
                    placeholder="维修日期"
                    v-model.trim="record.create_time"
                    @change="onChangeRepairDate"
                    :allow-clear="true"
                    style='width: 250px;height: 32px;'
                    :disabled="!canBeEdited || !isAdd"
                />
              </a-form-item>
              <a-form-item label="是否委外" style="width: 100%;margin: 5px 0;">
                <a-select
                    style='width: 150px'
                    allowClear
                    :disabled="!canBeEdited || !isAdd"
                    v-model.trim='record.is_outsource'
                    v-auth="`query`"
                >
                  <a-select-option
                      v-for='item in outsourceList'
                      :key='item.code'
                      :value='item.code'
                  >{{item.description}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="维修方法">
                <a-textarea v-model.trim='record.method'  :disabled="!canBeEdited || !isAdd" show-count style="width: 550px;margin-top: 6px" :maxlength="500" />
              </a-form-item>

              <a-form-item
                  label="实际用时(h)"
              >
                <a-input style='width: 200px;height: 32px' v-model.trim='record.real_cost_time' disabled v-auth="`query`"></a-input>
              </a-form-item>
              <a-form-item
                  label="计算实际用时(h)"
              >
                <a-input style='width: 200px;height: 32px' v-model.trim='record.real_cost_time_auto' disabled v-auth="`query`"></a-input>
              </a-form-item>
            </div>
          </a-form>
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;">
            <a-tabs type="card" :activeKey="tabKey"  :tabBarGutter="tabBarGutter" :tabBarStyle="tabBarStyle" style="width: 100%;">
              <a-tab-pane key="1" tab="备品领用" :force-render="true">
                <div style="width: 100%;display: flex;flex-direction: row;">
                  <div style="width: 100%;">
                    <a-table
                        :columns="detailColumnMain"
                        :data-source="detail1Data"
                        :pagination="detail1Pagination"
                        :scroll="{x:true,y: 165 }"
                    >
                      <template slot="action" slot-scope="record1">
                          <a>详情</a>
                      </template>
                    </a-table>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-spin>
      </a-modal>


      <!--弹窗0 新增按钮-->
      <a-modal
          destroyOnClose
          class="addModal"
          v-model='addModal'
          width='1200px'
          :title="isAdd?'新增维修':title"
          @ok="handleCancel0"
          @cancel="handleCancel0"
          :bodyStyle="bodyStyle"
          :loading="addLoading"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;">
            <a-table
                :columns="key1Columns"
                :data-source="key1Data"
                :pagination="key1Pagination"
                @change="onChangeKey1"
                :showPagination="true"
                :loading="key1Loading"
                style="width: 100%;"
                :scroll="{x:true,y: 165 }"
            >
              <template slot="action" slot-scope="record">
                  <a v-auth="`query`" @click="repairDevice(record)">设备维修</a>
              </template>
            </a-table>
          </div>
        </a-spin>

      </a-modal>
      <!--新增里的设备维修-->
      <a-modal
          destroyOnClose
          v-model='addDetailModel'
          width='800px'
          :title="isAdd?'设备维修详情':title"
          @ok="submit"
          @cancel="addDetailCancel"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;display: flex;flex-direction: row;margin-top: 10px">
            <a-form-model layout="inline"  class='query' style='display: flex;flex-wrap: wrap;'>
              <a-form-model-item
                  class='optionTitle'
                  label="设备编码"
                  style="margin-left: 15px"
              >
                <a-input style='width: 200px;height: 32px' v-model='record.device_code' disabled v-auth="`query`"></a-input>
              </a-form-model-item>
              <a-form-model-item
                  class='optionTitle'
                  label="设备名称"
                  prop="name"
              >
                <a-input style='width: 200px;height: 32px' v-model='record.device_name' disabled v-auth="`query`"></a-input>
              </a-form-model-item>
            </a-form-model>
          </div>
          <a-form layout="inline">
            <div style="margin:15px 2%;">
              <a-form-item label="故障原因" style="width: 100%;margin: 5px 0;">
                <a-textarea v-model.trim="addRepairDetailForm.fault_reason" show-count style="width: 550px" :maxlength="500" />
              </a-form-item>

              <a-form-item label="维修人" style="width: 100%;margin: 5px 0 5px 14px;">
                  <a-popover  trigger="click" placement="bottom" :overlayStyle="{ width: '250px' }">
                    <template slot="content">
                      <p class="aPopover" v-for="(item,index) in userSearchList" :key="index"  @click="changeUser(item)" >{{item.name}}</p>
                    </template>
                    <a-input style='width: 250px;height: 32px;'
                             v-model.trim="addRepairDetailForm.repair_person"
                             @keydown.enter="getUserList(addRepairDetailForm.repair_person)"
                             @change="getUserList(addRepairDetailForm.repair_person)"
                             allowClear
                             @click="getUserList(addRepairDetailForm.repair_person)"
                             v-auth="`query`" ></a-input>
                  </a-popover>
              </a-form-item>
              <a-form-item label="维修日期" style="width: 100%;">
                <a-date-picker
                    format="YYYY-MM-DD"
                    show-time
                    allowClear
                    placeholder="维修日期"
                    v-model.trim="addRepairDetailForm.repair_time"
                    @change="onChangeRepairDate"
                    :allow-clear="true"
                    style='width: 250px;height: 32px;'
                    :disabled="!canBeEdited || !isAdd"
                />
              </a-form-item>
              <a-form-item label="是否委外" style="width: 100%;margin: 5px 0;">
                <a-select
                    style='width: 150px'
                    allowClear
                    v-model.trim='addRepairDetailForm.is_outsource'
                    v-auth="`query`"
                >
                  <a-select-option
                      v-for='item in outsourceList'
                      :key='item.code'
                      :value='item.code'
                  >{{item.description}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="维修方法">
                <a-textarea v-model.trim='addRepairDetailForm.method' show-count style="width: 550px;margin-top: 6px" :maxlength="500" />
              </a-form-item>

              <a-form-item
                  label="实际耗时(h)"
              >
                <a-input style='width: 200px;height: 32px' v-model.trim='addRepairDetailForm.real_cost_time'  v-auth="`query`"></a-input>
              </a-form-item>
            </div>
          </a-form>
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;">
            <a-tabs type="card" :activeKey="tabKey"  :tabBarGutter="tabBarGutter" :tabBarStyle="tabBarStyle" style="width: 100%;">
              <a-tab-pane key="1" tab="备品领用" :force-render="true">
                <div style="width: 100%;display: flex;flex-direction: row;">
                  <div style="width: 100%;">
                    <div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
                      <a-input style='width: 125px;height: 32px;' v-model.trim="addPartForm.part_id" placeholder="*序号" disabled></a-input>

                      <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '125px' }">
                        <template slot="content">
                          <p class="aPopover" v-for="(item,index) in partSearchList" :key="index"  @click="changePart(item)" >{{
                              'code:'+item.code+',name:'+item.name}}</p>
                        </template>
                      <a-input style='width: 125px;height: 32px;'
                               v-model.trim="addPartForm.part_code"
                               placeholder="*编码(搜索)"
                               allowClear
                               @keydown.enter="getPartListByPartCode(addPartForm.part_code)"
                               @change="getPartListByPartCode(addPartForm.part_code)"
                               @click="getPartListByPartCode(addPartForm.part_code)"
                               :disabled="!canBeEdited || !isAdd"></a-input>
                      </a-popover>

                      <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '125px' }">
                        <template slot="content">
                          <p class="aPopover" v-for="(item,index) in partSearchList" :key="index"  @click="changePart(item)" >{{
                              'code:'+item.code+',name:'+item.name}}</p>
                        </template>
                          <a-input style='width: 125px;height: 32px;'
                                   v-model.trim="addPartForm.part_name" placeholder="*名称(搜索)"
                                   @keydown.enter="getPartListByPartName(addPartForm.part_name)"
                                   @change="getPartListByPartName(addPartForm.part_name)"
                                   allowClear
                                   @click="getPartListByPartName(addPartForm.part_name)"
                                   :disabled="!canBeEdited || !isAdd"></a-input>
                      </a-popover>

                      <a-input style='width: 125px;height: 32px;' v-model.trim="addPartForm.part_number"  placeholder="数量"  :disabled="!canBeEdited || !isAdd"></a-input>
                      <div style='width: 125px;display: flex;  justify-content:right;margin-left: 10px' >
                        <a-button type="primary" style="margin-right: 15px" @click="clearAddMessage" :disabled="!canBeEdited || !isAdd">重置</a-button>
                        <a-button type="primary" @click="addPart" :disabled="!canBeEdited || !isAdd || !this.addPartForm.part_id || ! this.addPartForm.part_number">添加</a-button>
                      </div>
                    </div>

                    <a-table
                        :columns="detail1Columns"
                        :data-source="addRepairDetailForm.parts_list"
                        :pagination="detail1Pagination"
                        :scroll="{x:true,y: 165 }"
                    >
                      <template slot="action" slot-scope="record1">
                        <a-popconfirm title="确定删除?" @confirm="delPart(record1)">
                          <a>删除</a>
                        </a-popconfirm>
                      </template>
                    </a-table>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-spin>

      </a-modal>

      <!--编辑-->
      <a-modal
          destroyOnClose
          v-model='editModal'
          width='800px'
          :title="canBeQuery?'编辑':title"
          @ok="submitEdit"
          @cancel="editHandleCancel"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
          <div style="width: 100%;display: flex;flex-direction: row;margin-top: 10px">
            <a-form-model layout="inline"  class='query' style='display: flex;flex-wrap: wrap;'>
              <a-form-model-item
                  class='optionTitle'
                  label="设备编码"
                  style="margin-left: 15px"
              >
                <a-input style='width: 200px;height: 32px' v-model='record.device_code'  disabled v-auth="`query`"></a-input>
              </a-form-model-item>
              <a-form-model-item
                  class='optionTitle'
                  label="设备名称"
                  prop="name"
              >
                <a-input style='width: 200px;height: 32px' v-model='record.device_name'  disabled v-auth="`query`"></a-input>
              </a-form-model-item>
            </a-form-model>
          </div>
          <a-form layout="inline">
            <div style="margin:15px 2%;">
              <a-form-item label="故障原因" style="width: 100%;margin: 5px 0;">
                <a-textarea v-model.trim="record.fault_reason"
                            :disabled="!canBeEdited || !isAdd"
                            show-count style="width: 550px" :maxlength="500" />
              </a-form-item>

              <a-form-item label="维修人" style="width: 100%;margin: 5px 0 5px 14px;">
                <a-input style='width: 250px;height: 32px;'
                         disabled
                         v-model.trim="record.create_user_name"
                         v-auth="`query`" ></a-input>
              </a-form-item>
              <a-form-item label="维修日期" style="width: 100%;">
                <a-date-picker
                    format="YYYY-MM-DD"
                    show-time
                    allowClear
                    placeholder="维修日期"
                    v-model.trim="record.create_time"
                    @change="onChangeRepairDate"
                    :allow-clear="true"
                    style='width: 250px;height: 32px;'
                    :disabled="!canBeEdited || !isAdd"
                />
              </a-form-item>
              <a-form-item label="是否委外" style="width: 100%;margin: 5px 0;">
                <a-select
                    style='width: 150px'
                    allowClear
                    :disabled="!canBeEdited || !isAdd"
                    v-model.trim='record.is_outsource'
                    v-auth="`query`"
                >
                  <a-select-option
                      v-for='item in outsourceList'
                      :key='item.code'
                      :value='item.code'
                  >{{item.description}}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="维修方法">
                <a-textarea v-model.trim='record.method'  :disabled="!canBeEdited || !isAdd" show-count style="width: 550px;margin-top: 6px" :maxlength="500" />
              </a-form-item>

              <a-form-item
                  label="实际用时(h)"
              >
                <a-input style='width: 200px;height: 32px' v-model.trim='record.real_cost_time' :disabled="!canBeEdited || !isAdd" v-auth="`query`"></a-input>
              </a-form-item>
              <a-form-item
                  label="计算实际用时(h)"
              >
                <a-input style='width: 200px;height: 32px' v-model.trim='record.real_cost_time_auto' disabled v-auth="`query`"></a-input>
              </a-form-item>
            </div>
          </a-form>
          <!--标签页-->
          <div style="width: 100%;min-height: 250px;display: flex;flex-direction: row;padding: 10px 24px 0px 24px;">
            <a-tabs type="card" :activeKey="tabKey"  :tabBarGutter="tabBarGutter" :tabBarStyle="tabBarStyle" style="width: 100%;">
              <a-tab-pane key="1" tab="备品领用" :force-render="true">
                <div style="width: 100%;display: flex;flex-direction: row;">
                  <div style="width: 100%;">
                    <a-table
                        :columns="detailColumnMain"
                        :data-source="detail1Data"
                        :pagination="detail1Pagination"
                        :loading ="detailTableLoading"
                        :scroll="{x:true,y: 165 }"
                    >
                      <template slot="action" slot-scope="record1">
                        <a-popconfirm title="确定删除?" @confirm="delPartReceive(record1)">
                           <a>删除</a>
                        </a-popconfirm>
                      </template>
                    </a-table>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-spin>
      </a-modal>

      <page-head-area>
        <div class="extra" style="width: 260px;display: flex;justify-content: space-around">
<!--          <a-badge count="9">-->
            <a-button icon="plus-circle" v-auth="`insert`" @click="add" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">新增</a-button>
<!--          </a-badge>-->
          <a-popconfirm title="批量删除?" @confirm="deleteSelect">
              <a-button icon="delete" v-auth="`delete`" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">删除</a-button>
          </a-popconfirm>
          <a-popconfirm title="批量审核?" @confirm="auditSelect">
             <a-button icon="audit"  style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">审核</a-button>
          </a-popconfirm>
        </div>
      </page-head-area>

      <div class="queryBox">
        <a-form-model layout="inline" :model='queryForm' class='query' style='display: flex;flex-wrap: wrap;'>
          <a-form-model-item
              class='optionTitle'
              label="设备编码"
              style="margin-left: 0"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.device_code' v-auth="`query`"></a-input>
          </a-form-model-item>
          <a-form-model-item
              class='optionTitle'
              label="设备名称"
              prop="name"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.device_name' v-auth="`query`"></a-input>
          </a-form-model-item>


          <a-form-model-item
              label="审核状态"
          >
            <a-select
                style='width: 150px'
                allowClear
                v-model.trim='queryForm.audit_status'
                v-auth="`query`"
            >
              <a-select-option
                  v-for='item in auditStatusList2'
                  :key='item.code'
                  :value='item.code'
              >{{item.description}}</a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item
              label="日期范围"
          >
            <a-range-picker
                :valueFormat="'YYYY-MM-DD'"
                style="width: 300px;"
                :format="'YYYY-MM-DD'"
                v-model.trim="queryForm.dateSelect"
                :allow-clear="true"/>
          </a-form-model-item>

          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="reset" v-auth="`query`">
              重置
            </a-button>
          </a-form-model-item>
          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="filter" v-auth="`query`">
              搜索
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="dataBox">
        <a-table
            :columns="columns"
            :data-source="data"
            :pagination="false"
            :loading="tableLoading"
            :rowKey="(recordS) => {return recordS.id}"
            :scroll="{ x: 1000, y: 500 }"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="action" slot-scope="record">
            <div v-if="record.status===1">
              <a v-auth="`query`" @click="detail(record)">详情</a>
            </div>

            <div v-if="record.status===0">
              <a-popconfirm title="审核通过?" @confirm="saveOneAudit(record)">
                 <a v-auth="`update`">审核</a>
              </a-popconfirm>
              <a-divider type="vertical"/>
              <a v-auth="`update`" @click="edit(record)">编辑</a>
            </div>

          </template>
        </a-table>

      </div>

      <a-pagination
          @change="onChangePage"
          @showSizeChange="showSizeChange"
          :total="pagination.total"
          :showSizeChanger="true"
          :showQuickJumper="true"
          :defaultPageSize="pagination.defaultPageSize"
          :pageSize="pagination.page_size"
          :pageSizeOptions="pagination.pageSizeOptions"
          :current="pagination.current"
          :showTotal="pagination.showTotal"
          style="width: 100%;display: flex;flex-direction: row;justify-content: flex-end;margin-top: 15px"
      ></a-pagination>
    </a-card>
  </div>
</template>

<script>

import {mapGetters} from "vuex";
import PageHeadArea from "../module/pageHeadArea.vue";
import pagination from "ant-design-vue/lib/pagination";
import storage from "store";
import {DEPT_ID, ORGANIZATION_ID, USER_TOKEN} from "@/store/mutation-types";
import axios from "axios";
import moment from "moment";
import {
  file_import, file_upload,
  get_employee_list,
  get_extended_define, get_asset_file_list, get_supplier, get_unit_list, download_file,
  get_organization_list,
  delete_asset, get_asset_list, save_asset, update_asset,
  get_category_type_list, get_organization_profile_list, get_template_list, update_extend
} from "@/services/manage";
import {
  deleteDeviceRepair, deleteDeviceRepairSparePartsReceiveRelation, deleteSparePartsReceive,
  getCacheByVaguename,
  getCurrentUserInfo,
  getDeviceList, getPartsById,
  getUserNameById,
  listDeviceRepairAll,
  listDeviceRepairOrderAll,
  listDeviceRepairOrderByUserId, listDeviceRepairSparePartsReceiveRelation,
  listSpareParts, listSparePartsInventory, listSparePartsReceive,
  saveDeviceRepair,
  saveDeviceRepairOrder,
  saveDeviceRepairSparePartsReceiveRelation, saveSparePartsReceive
} from "../../utils/interface";
import {message} from "ant-design-vue";
import {list_device_repair_all} from "../../services/deviceRepair";
const data = []
const columns = [
  { title: '维修单号', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '设备编码', width: 120, align:'center',dataIndex: 'device_code', key: 'device_code'},
  { title: '设备名称', width: 120, align:'center',dataIndex: 'device_name', key: 'device_name'},
  { title: '维修日期', width: 120, align:'center',dataIndex: 'create_time', key: 'create_time'},
  { title: '维修人', width: 120, align:'center',dataIndex: 'create_user_name', key: 'create_user_name'},
  { title: '是否委外', width: 120, align:'center',dataIndex: 'is_outsource_name', key: 'is_outsource_name'},
  { title: '实际用时', width: 120, align:'center',dataIndex: 'real_cost_time', key: 'real_cost_time'},
  { title: '计算实际用时', width: 120, align:'center',dataIndex: 'real_cost_time_auto', key: 'real_cost_time_auto'},
  { title: '故障原因', width: 120, align:'center',dataIndex: 'fault_reason', key: 'fault_reason'},
  { title: '维修方法', width: 120, align:'center',dataIndex: 'method', key: 'method'},
  { title: '状态', width: 120, align:'center',dataIndex: 'status_name', key: 'status_name'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]
const detailColumnMain = [
  { title: '序号', width: 120, align:'center',dataIndex: 'id', key: 'id'},
  { title: '编码', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'part_name', key: 'part_name'},
  { title: '数量', width: 120, align:'center',dataIndex: 'quantity', key: 'quantity'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

const key1Columns = [
  { title: '序号', width: 120, align:'center',dataIndex: 'id', key: 'id'},
  { title: '报修单号', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '设备编码', width: 120, align:'center',dataIndex: 'device_code', key: 'device_code'},
  { title: '报修人', width: 120, align:'center',dataIndex: 'create_user_name', key: 'create_user_name'},
  { title: '设备名称', width: 120, align:'center',dataIndex: 'device_name', key: 'device_name'},
  { title: '报修日期', width: 120, align:'center',dataIndex: 'create_time', key: 'create_time'},
  { title: '故障原因', width: 120, align:'center',dataIndex: 'fault_reason', key: 'fault_reason'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
  ]

const detail1Columns=[
  { title: '序号', width: 120, align:'center',dataIndex: 'part_id', key: 'part_id'},
  { title: '编码', width: 120, align:'center',dataIndex: 'part_code', key: 'part_code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'part_name', key: 'part_name'},
  { title: '数量', width: 120, align:'center',dataIndex: 'part_number', key: 'part_number'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

const key1Data =[];
const detail1Data=[]

export default {
  name: "userAuthority",
  components: {PageHeadArea},
  data() {
    return {
      detailTableLoading:false,
      editModal:false,
      detailColumnMain,
      addLoading:false,
      partSearchList:[],
      addPartForm:{
        part_id:undefined,
        part_code:undefined,
        part_name:undefined,
        part_number:undefined,
      },
      outsourceList:[
        { code: 0, description: "否" },
        { code: 1, description: "是" }],
      addRepairDetailForm:{
        real_cost_time:undefined,
        fault_reason:'',
        repair_person:undefined,
        repair_person_id:undefined,
        repair_time:undefined,
        is_outsource:undefined,
        method:'',
        parts_list:[]
      },
      userSearchList:[],
      addDetailModel:false,
      record:{},
      key1Loading:false,
      queryForm: {
        device_code: '',
        device_name: '',
        audit_status:undefined,
        dateSelect:[],
      },
      selectedRowKeys:[],
      auditStatusList2:[
        {code:null,description: '不限'},
        { code: 0, description: "未审核" },
        { code: 1, description: "已审核" }],
      auditStatusList:[
        { code: 0, description: "未审核" },
        { code: 1, description: "已审核" }],
      key1Data,
      key1Columns,
      detail1Columns,
      detail1Data,
      tableLoading01: false,
      axiosSource: null,
      tabKey: '1',
      title:'',
      tabBarGutter: 0,
      tabBarStyle: {
        color: 'rgba(0, 0, 0, 0.85)'
      },
      bodyStyle: {
        'padding': '0px 24px 0px 24px',
        'font-size': '14px',
        'line-height': '1.5',
        'word-wrap': 'break-word',
      },
      cardMinHeight: 0,
      statusList: [
        // {id: 1, name: '待采购', code: '0', type: 'use_status'},
        {id: 1, name: '正常运行', code: '1',type: 'use_status'},
        {id: 2, name: '不正常运行', code: '2',type: 'use_status'},
      ],
      data,
      columns,
      pagination: {
        total: 0,
        page_size: 10,
        defaultPageSize: 10,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '50', '100', '500'],
      },
      detail1Pagination:{
        total: 0,
        page_size: 10,
        defaultPageSize: 10,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '50', '100', '500'],
      },
      tableLoading: false,
      addModal: false,
      canBeEdited: false, //是否可编辑
      isAdd: false, //是否为新增
      spinning: false,

      detailModal:false, //详情弹窗
      canBeQuery:false, //是否可查询

      remodelModal:false,
      disposalModal:false,
      maintenance_detailsModal:false,
      key1Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      }
    }
  },
  watch: {},
  authorize: {
    add: 'insert',
    getAssetLedgerList: 'query',
    reset: 'query',
    query: 'query',
    detail: 'query',
    edit: 'update',
    del: 'delete',
    check: 'check',
  },
  computed: {
    ...mapGetters(['getCardMinHeight']),
  },
  created() {
    this.cardMinHeight = this.getCardMinHeight
  },
  async mounted() {
    this.axiosSource = axios.CancelToken.source();

    await this.initialize()

  },
  methods: {
    delPart(record){

      this.addRepairDetailForm.parts_list = this.addRepairDetailForm.parts_list.filter(item => item !== record);
    },
    onSelectChange(selectedRowKeys){
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys
    },
    async auditSelect() {
      for (const item of this.selectedRowKeys) {
        await saveDeviceRepair({'id': item,'status':1})
      }
      this.selectedRowKeys=[]
      message.success('审核成功')
      await this.initialize()
    },
    async deleteSelect() {
      for (const item of this.selectedRowKeys) {
        await deleteDeviceRepair({'id': item})
      }
      this.selectedRowKeys = []
      message.success('删除成功')
      await this.initialize()
    },
    async saveOneAudit(record) {
      await saveDeviceRepair({'id': record.id, 'status': 1})
      message.success('审核成功')
      await this.initialize()
    },
    changePart(item){
      this.addPartForm={
        part_id:item.id,
        part_code:item.code,
        part_name:item.name,
      }
      this.partSearchList=[]
    },
    async delPartReceive(record1) {
      // console.log(record1)
      //删device_repair_spare_parts_receive_relation  device_repair_id spare_parts_receive_id
      this.detailTableLoading=true
      let searchRelation = await listDeviceRepairSparePartsReceiveRelation({
        'device_repair_id': this.record.id,
        'spare_parts_receive_id': record1.id
      })

      // deleteDeviceRepairSparePartsReceiveRelation
      await deleteDeviceRepairSparePartsReceiveRelation({'id': searchRelation[0].id})
      //删 spare_parts_receive
      await deleteSparePartsReceive({'id': record1.id})
      //刷新
      await this.detail1DataIni()
      this.detailTableLoading=false
      message.success('删除成功')


    },
    addDetailCancel(){
      this.addDetailModel=false
    },
    addPart(){
      //查重
      const isDuplicate = this.addRepairDetailForm.parts_list.some(item => item.part_id === this.addPartForm.part_id);
      if (isDuplicate) {
        message.error('该备品已添加')
        return;
      }
      this.addRepairDetailForm.parts_list.push(this.addPartForm)
      this.clearAddMessage()
    },
    onChangeRepairDate(value, dateString){
      this.addRepairDetailForm.repair_time = dateString
    },
    async getPartListByPartCode(part_code){
      await listSpareParts({'code': part_code}).then(res => {
        this.partSearchList = []
        res.slice(0, 10).forEach(item => {
          this.partSearchList.push({
            id: item.id,
            code:item.code,
            name: item.name
          })
        })
      })
    },
    async getPartListByPartName(part_name) {
      await listSpareParts({'name': part_name}).then(res => {
        this.partSearchList = []
        res.slice(0, 10).forEach(item => {
          this.partSearchList.push({
            id: item.id,
            code:item.code,
            name: item.name
          })
        })
      })
    },
    repairDevice(record){
      this.record=record
      this.addDetailModel =true
      this.clearAddMessage()
      this.clearAddMain()


    },
    clearAddMain(){
      this.addRepairDetailForm ={
            real_cost_time:undefined,
            fault_reason:'',
            repair_person:undefined,
            repair_person_id:undefined,
            repair_time:undefined,
            is_outsource:undefined,
            method:'',
            parts_list:[]
      }
      this.userSearchList=[]
    },
    changeUser(item){
      this.addRepairDetailForm.repair_person=item.name;
      this.addRepairDetailForm.repair_person_id= item.id
      // console.log(record1)
      this.userSearchList=[]
    },
    async getUserList(order_user) {
      this.userSearchList = []
      await getCacheByVaguename(order_user).then(res=>{
        res.slice(0, 10).forEach(item => {
          this.userSearchList.push({
            id: item.id,
            name: item.name
          })
        })
      })
      // console.log(this.userSearchList)
    },
    reset() {
      this.queryForm = {
        device_code: '',
        device_name: '',
        audit_status:undefined,
        dateSelect:[],
      }
      this.query()
    },
    clearAddMessage(){
      this.addPartForm={
        part_id:undefined,
        part_code:undefined,
        part_name:undefined,
        part_number:undefined,
      }
      this.partSearchList=[]

    },
    detailHandleCancel(){
      this.detailModal=false
      this.clearAddMain()
    },
    async filter() {
      //筛选
      this.pagination.page = 1
      this.pagination.current = 1
      this.pagination.page_size = 10
      this.tableLoading = true
      // 获取时间范围
      await this.initialize({
        'status':this.queryForm.audit_status
      })
      const [startDate, endDate] = this.queryForm.dateSelect;
      this.data = this.data.filter(item => {
        // 检查每个条件是否满足
        return (
            (this.queryForm.device_code ? item.device_code.includes(this.queryForm.device_code) : true) &&
            (this.queryForm.device_name ? item.device_name.includes(this.queryForm.device_name) : true) &&
            (startDate ? new Date(item.create_time) >= new Date(startDate) : true) &&
            (endDate ? new Date(item.create_time) <= new Date(endDate) : true)
        );
      });
      this.tableLoading = false;
    },
    onChangePage (page, pageSize) {
      this.pagination.current = page
      this.pagination.page_size = pageSize
      this.pagination.page = page
      this.initialize()
    },
    showSizeChange(current, size){
      this.pagination.page_size = size
      this.pagination.current = current
      this.pagination.page = current
      this.initialize()
    },
    async initialize(params) {
      this.data=[]
      this.tableLoading =true
      const paramsAll = Object.assign({}, params, {
        "page": this.pagination.page,
        "page_size": this.pagination.page_size
      });

      await list_device_repair_all(paramsAll).then(async res => {
        console.log(res)
        // console.log(res)
        if(res.data.code === '1000'){
          this.pagination.total = res.data.extension.total+(this.pagination.current-1)*this.pagination.page_size
          for (const item of res.data.data) {
            let searchDevice = await getDeviceList({'id': item.device_id})
            item['device_name'] = searchDevice[0]?.name || ''
            item['device_code'] = searchDevice[0]?.code || ''
            item['create_user_name'] = await getUserNameById(item.create_user)
            if(item.is_outsource===0){
              item['is_outsource_name'] = '否'
            }else {
              item['is_outsource_name'] = '是'
            }
            let searchOrder = await listDeviceRepairOrderAll({'id':item.order_id})
            item['fault_reason'] = searchOrder[0].fault_reason
            item['status_name'] = this.auditStatusList.find(it=>it.code===item.status)?.description || ''
            //维修责任人
            item['create_user_name'] = await getUserNameById(item.create_user)
          }
        }
        this.data = res.data.data
      })
      this.tableLoading =false
    },
    onChangeDate(date, dateString) {
      console.log(date, dateString);
    },
    // 分页切换
    onChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.page_size = pagination.pageSize
      this.pagination.page = pagination.current
      this.getAssetLedgerList()
    },
    // 分页切换
    onChangeKey1 (pagination) {
      this.key1Pagination.current = pagination.current
      this.key1Pagination.page_size = pagination.pageSize
      this.key1Pagination.page = pagination.current
    },
    onChangeDetail1(pagination){
      this.detail1Pagination.current = pagination.current
      this.detail1Pagination.page_size = pagination.pageSize
      this.detail1Pagination.page = pagination.current
    },
    async query() {
      this.queryForm={
        device_code: '',
        device_name: '',
        audit_status:undefined,
        dateSelect:[],
      }
      this.tableLoading = true
      this.pagination.page = 1
      this.pagination.current = 0
      this.pagination.page_size = 10
      await this.initialize()
      this.tableLoading = false
    },
    add() {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
      //查询给自己的维修单
      this.getMyRepairOrderList()
    },
    async getMyRepairOrderList() {
      this.key1Data = []
      let user = await getCurrentUserInfo()
      //user_id
      let user_id = user.user_id
      this.key1Loading = true


      await listDeviceRepairOrderByUserId({'user_id':user_id}).then(async res => {
        for (const item of res) {
          if(item.status===0){
            let searchDevice = await getDeviceList({'id': item.device_id})
            item['device_name'] = searchDevice[0]?.name || ''
            item['device_code'] = searchDevice[0]?.code || ''
            item['create_user_name'] = await getUserNameById(item.create_user)
            this.key1Data.push(item)
          }

        }

      })
      this.key1Loading = false
    },
    del(id) {
      const params = Object.assign({},{'organization_id': storage.get(ORGANIZATION_ID),'asset_id': id})
      delete_asset(params)
          .then(res => {
            if (res && res.data.code && res.data.code === '1000') {
              this.getAssetLedgerList()
            } else {
              this.$message.error('删除失败',1)
            }
          })
          .catch(err => {
            console.log(err)
            this.$message.error('删除失败',1)
          })
    },
    async submitEdit() {
      // console.log(this.record)
      //保存
      this.editHandleCancel()
      console.log({
        'id': this.record.id,
        'fault_reason':this.record.fault_reason,
        'create_time':this.record.create_time,
        'is_outsource':this.record.is_outsource,
        'method':this.record.method,
        'real_cost_time':this.record.real_cost_time
      })
      await saveDeviceRepair({
        'id': this.record.id,
        'fault_reason':this.record.fault_reason,
        'create_time':this.record.create_time,
        'is_outsource':this.record.is_outsource,
        'method':this.record.method,
        'real_cost_time':this.record.real_cost_time
      })

      message.success('编辑成功')
      await this.initialize()
    },
    editHandleCancel(){
      this.editModal = false
      this.canBeEdited = false
      this.isAdd = false
      this.canBeQuery = false
    },
    async edit(record) {
      this.editModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.canBeQuery = true
      this.record = record
      await this.detail1DataIni()
    },
    async detail1DataIni(){
      //添加数据 detail1Data 备品领用
      this.detail1Data = []
      await listDeviceRepairSparePartsReceiveRelation({'device_repair_id': this.record.id}).then(async res => {
        if(res==='NoData' || res==='Error'){
          this.detail1Data = []
        }
        else{
          for (const it of res) {
          await listSparePartsReceive({'id':it.spare_parts_receive_id}).then(async receiveIt => {

            await listSparePartsInventory({'id': receiveIt.inventory_id}).then( async inventory => {
              let part = await getPartsById({'id': inventory.spare_parts_id})
              receiveIt[0]['part_name'] = part[0].name
            })
            this.detail1Data.push(receiveIt[0])
          })
        }}

      })
    },
    async detail(record) {
      this.detailModal = true
      this.canBeEdited = false
      this.canBeQuery = true
      this.isAdd = false
      this.record = record
      await this.detail1DataIni()
    },
    remodel(record){
      this.remodelModal = true
      this.canBeEdited = false
      this.canBeQuery =true
      this.isAdd = false
      this.echo(record)
    },
    disposal(record){
      this.disposalModal = true
      this.canBeEdited = false
      this.canBeQuery =true
      this.isAdd = false
      this.echo(record)
    },
    clearParameter() {},
    handleCancel() {
      this.tabKey = '1'
    },
    handleCancel0() {
      this.addModal = false
      this.canBeEdited = false
      this.isAdd = false
    },
    handleCancel1(){
      this.detailModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    handleCancel2(){
      this.disposalModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    sortInventoryByQuantity(inventory) {
      return inventory.sort((a, b) => b.quantity - a.quantity);
    },
    generateUniqueCode() {
      // 使用当前时间戳和随机数生成唯一代码
      const timestamp = Date.now().toString();
      const randomNum = Math.floor(Math.random() * 10000).toString();
      return `ORD-${timestamp}-${randomNum}`;
    },
    async submit() {

      // if (this.addRepairDetailForm.fault_reason === '') {
      //   message.error('请输入故障原因')
      //   return
      // }
      //
      // if (this.addRepairDetailForm.repair_person_id === undefined) {
      //   message.error('请选择维修人员')
      //   return
      // }
      // if (this.addRepairDetailForm.repair_time === undefined) {
      //   message.error('请选择维修时间')
      //   return
      // }
      //
      // if (this.addRepairDetailForm.is_outsource === undefined) {
      //   message.error('请选择是否外派')
      //   return
      // }
      // if (this.addRepairDetailForm.method === '') {
      //   message.error('请输入维修方法')
      //   return
      // }
      // if (this.addRepairDetailForm.real_cost_time === undefined) {
      //   message.error('请输入实际用时')
      //   return
      // }

        //添加
        message.info("开始添加,请稍等")
        this.addLoading = true
        await saveDeviceRepair({
          'order_id':this.record.id,
          'code':this.record.code,
          'device_id':this.record.device_id,
          'repair_time':this.addRepairDetailForm.repair_time,
          'is_outsource':this.addRepairDetailForm.is_outsource,
          'real_cost_time':this.addRepairDetailForm.real_cost_time,
          'method':this.addRepairDetailForm.method,
          'create_user':this.addRepairDetailForm.repair_person_id
        })

        //拿repair_id
        let searchRepair = await listDeviceRepairAll({'code':this.record.code})
        let repair_id = searchRepair[0].id


        //改reason
        await saveDeviceRepairOrder({'id':this.record.id,'fault_reason':this.addRepairDetailForm.fault_reason})

        //放part
        for (const it of this.addRepairDetailForm.parts_list) {
          //根据part_id找库存量
          //获取所有库存信息
          let inventory_all = await listSparePartsInventory({'spare_parts_id':it.part_id})

          //根据库存量排序
          let sort_result = this.sortInventoryByQuantity(inventory_all);

          //库存列表
          let inventory_list = []
          //计算 获得 inventory_list ->> inventory_id
          let addSum=0
          for (let i = 0; i < sort_result.length; i++) {
            let inItem = sort_result[i];
            addSum += inItem.quantity;
            if (addSum >= it.part_number) {
              if (addSum === it.part_number) {
                inventory_list.push({'id': inItem.id, 'quantity': inItem.quantity});
              } else {
                //多了
                inventory_list.push({'id': inItem.id, 'quantity': it.part_number - (addSum - inItem.quantity)});
              }
              break;
            } else {
              inventory_list.push({'id': inItem.id, 'quantity': inItem.quantity});
            }
          }

          //插receive表
          let code_list = []
          for (const inIt of inventory_list) {
            let code = this.generateUniqueCode()
            code_list.push(code)

            await saveSparePartsReceive({
              'code':code,
              'inventory_id':inIt.id,
              'quantity':inIt.quantity,
              'receive_time':this.addRepairDetailForm.repair_time,
              'device_id':this.record.device_id,
              'receiver_id':this.addRepairDetailForm.repair_person_id
            })
          }
          // console.log(code_list)
          //拿receive_id
          let receive_id_list = []
          for (const codeIt of code_list) {
            let res = await listSparePartsReceive({'code':codeIt})
            receive_id_list.push(res[0].id)
          }
          // console.log(receive_id_list)

          //插device_repair_spare_parts_receive_relation表
          for (const receive_id of receive_id_list) {
            await saveDeviceRepairSparePartsReceiveRelation({
              'device_repair_id':repair_id,
              'spare_parts_receive_id':receive_id
            })
          }


        }
        this.addLoading = false
        await this.initialize()
        message.success("添加成功")
        this.addDetailCancel()

    },
  },
  beforeDestroy() {
    if (this.axiosSource) {
      this.axiosSource.cancel('Request canceled due to page navigation.');
    }
  }
}
</script>

<style scoped lang="less">
.aPopover{
}
.aPopover:hover {
  background-color: #EA5413;
}


.dataBox{
  margin-top: 20px;
}

.hide-scrollbar::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}
.hide-scrollbar {
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
  overflow-y: scroll; /* 保持内容可滚动 */
}
.demo-infinite-container {
  margin-top: 0px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 300px;
}
/deep/ .ant-form-inline .ant-form-item-with-help{
  margin-bottom: 0px;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #f5f5f5;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .unit .ant-select-selection--single{
  margin-left: 0px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: 0;
}
/deep/ .ant-select-disabled .ant-select-selection {
  background-color: #fff;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .ant-input-number-disabled{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
</style>